<!-- src/views/ProductSearch.vue -->
<template>
  <div class="product-search">
    <div class="search-header">
      <h1>🔍 商品搜索</h1>
      <p>找到您心仪的白酒</p>
    </div>

    <!-- 搜索栏 -->
    <SearchBar @search="handleSearch" @filter="handleFilter" @reset="handleReset" :reset-key="resetKey" />

    <!-- 搜索结果统计 -->
    <div class="search-stats" v-if="searchResults.length > 0 || hasSearched">
      <div class="stats-info">
        <span class="results-count"> 找到 {{ searchResults.length }} 款商品 </span>
        <span class="search-term" v-if="currentSearchTerm"> 搜索: "{{ currentSearchTerm }}" </span>
      </div>

      <div class="sort-options">
        <label>排序:</label>
        <select v-model="sortBy" @change="sortProducts">
          <option value="default">默认排序</option>
          <option value="price-asc">价格从低到高</option>
          <option value="price-desc">价格从高到低</option>
          <option value="name">名称排序</option>
          <option value="year">年份排序</option>
        </select>
      </div>
    </div>

    <!-- 搜索结果 -->
    <div class="search-results" v-if="searchResults.length > 0">
      <div class="products-grid">
        <ProductCard v-for="product in sortedResults" :key="product.id" :product="product" @view-details="viewProductDetails" @add-to-cart="addToCart" />
      </div>
    </div>

    <!-- 无结果提示 -->
    <div class="no-results" v-else-if="hasSearched">
      <div class="no-results-content">
        <div class="no-results-icon">😔</div>
        <h3>抱歉，没有找到相关商品</h3>
        <p>请尝试：</p>
        <ul>
          <li>检查拼写是否正确</li>
          <li>使用更通用的关键词</li>
          <li>尝试不同的筛选条件</li>
        </ul>
        <button class="btn btn-primary" @click="showAllProducts">查看所有商品</button>
      </div>
    </div>

    <!-- 默认显示所有商品 -->
    <div class="all-products" v-else>
      <div class="section-header">
        <h2>🍶 所有商品</h2>
        <p>浏览我们精选的白酒收藏</p>
      </div>

      <div class="products-grid">
        <ProductCard v-for="product in products" :key="product.id" :product="product" @view-details="viewProductDetails" @add-to-cart="addToCart" />
      </div>
    </div>

    <!-- 商品详情弹窗 -->
    <div class="modal" v-if="showModal" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ selectedProduct?.name }}</h3>
          <button class="close-btn" @click="closeModal">×</button>
        </div>

        <div class="modal-body" v-if="selectedProduct">
          <div class="product-detail-grid">
            <div class="product-image-large">
              <img :src="selectedProduct.image" :alt="selectedProduct.name" />
            </div>

            <div class="product-details">
              <!-- <div class="detail-item"><strong>类型:</strong> {{ selectedProduct.type }}</div> -->
              <div class="detail-item"><strong>类型:</strong> {{ selectedProduct.origin }}</div>
              <div class="detail-item"><strong>度数:</strong> {{ selectedProduct.alcohol }}度</div>
              <div class="detail-item">
                <strong>价格:</strong> <span class="price">¥{{ selectedProduct.price }}</span>
              </div>
              <div class="detail-item description">
                <strong>描述:</strong>
                <p>{{ selectedProduct.description }}</p>
              </div>

              <div class="modal-actions">
                <button class="btn btn-primary" @click="addToCartFromModal">加入购物车</button>
                <button class="btn btn-secondary" @click="closeModal">关闭</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useWineStore } from '@/store'
import SearchBar from '@/components/SearchBar.vue'
import ProductCard from '@/components/ProductCard.vue'
import { useGoods } from '@/composables/useGoods'

const { loadFeaturedGoods, loadGoodsList } = useGoods()

const resetKey = ref(Date.now()) // 用于强制重置 SearchBar 组件的状态
const store = useWineStore()

const searchResults = computed(() => store.searchResults)
const products = computed(() => store.products)

const hasSearched = ref(false)
const currentSearchTerm = ref('')
const sortBy = ref('default')
const showModal = ref(false)
const selectedProduct = ref(null)

const handleSearch = query => {
  hasSearched.value = true
  currentSearchTerm.value = query
  store.searchProducts(query)
}

const handleFilter = filters => {
  hasSearched.value = true
  currentSearchTerm.value = ''
  store.filterProducts(filters)
}

const handleReset = () => {
  hasSearched.value = false
  currentSearchTerm.value = ''
  sortBy.value = 'default'
  store.searchResults = []
  store.resetFilters?.()
  resetKey.value = Date.now() // 每次点击都更新，触发子组件响应

  // 你可以根据 store 的结构补充清除筛选条件的逻辑
}

const showAllProducts = () => {
  hasSearched.value = false
  currentSearchTerm.value = ''
  store.searchResults = []
}

const sortedResults = computed(() => {
  const results = [...searchResults.value]

  switch (sortBy.value) {
    case 'price-asc':
      return results.sort((a, b) => a.price - b.price)
    case 'price-desc':
      return results.sort((a, b) => b.price - a.price)
    case 'name':
      return results.sort((a, b) => a.name.localeCompare(b.name))
    case 'year':
      return results.sort((a, b) => b.year - a.year)
    default:
      return results
  }
})

const sortProducts = () => {
  // 排序逻辑已在 computed 中处理
}

const viewProductDetails = product => {
  selectedProduct.value = product
  showModal.value = true
}

const addToCart = product => {
  alert(`${product.name} 已加入购物车！`)
}

const addToCartFromModal = () => {
  if (selectedProduct.value) {
    addToCart(selectedProduct.value)
    closeModal()
  }
}

const closeModal = () => {
  showModal.value = false
  selectedProduct.value = null
}

onMounted(() => {
  // 初始化时显示所有商品
  store.searchResults = []
  loadFeaturedGoods()
  loadGoodsList()
  console.log('搜索页面products 内容：', products.value)
})
</script>

<style scoped>
.product-search {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.search-header {
  text-align: center;
  margin-bottom: 40px;
}

.search-header h1 {
  font-size: 2.5rem;
  color: #2c3e50;
  margin-bottom: 10px;
}

.search-header p {
  font-size: 1.2rem;
  color: #666;
}

.search-stats {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  background: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.stats-info {
  display: flex;
  gap: 20px;
  align-items: center;
}

.results-count {
  font-weight: bold;
  color: #2c3e50;
  font-size: 1.1rem;
}

.search-term {
  color: #8b4513;
  font-style: italic;
}

.sort-options {
  display: flex;
  align-items: center;
  gap: 10px;
}

.sort-options label {
  font-weight: bold;
  color: #333;
}

.sort-options select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 14px;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 30px;
  margin-bottom: 40px;
}

.no-results {
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 15px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.no-results-content {
  max-width: 400px;
  margin: 0 auto;
}

.no-results-icon {
  font-size: 4rem;
  margin-bottom: 20px;
}

.no-results h3 {
  color: #2c3e50;
  margin-bottom: 20px;
  font-size: 1.5rem;
}

.no-results p {
  color: #666;
  margin-bottom: 15px;
}

.no-results ul {
  text-align: left;
  color: #666;
  margin-bottom: 30px;
  padding-left: 20px;
}

.no-results li {
  margin-bottom: 8px;
}

.section-header {
  text-align: center;
  margin-bottom: 40px;
}

.section-header h2 {
  font-size: 2rem;
  color: #2c3e50;
  margin-bottom: 10px;
}

.section-header p {
  font-size: 1.1rem;
  color: #666;
}

/* 模态框样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 15px;
  max-width: 800px;
  width: 90%;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  color: #2c3e50;
  font-size: 1.5rem;
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  font-size: 2rem;
  cursor: pointer;
  color: #999;
  transition: color 0.3s;
}

.close-btn:hover {
  color: #333;
}

.modal-body {
  padding: 30px;
}

.product-detail-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 40px;
}

.product-image-large img {
  width: 100%;
  height: auto;
  border-radius: 10px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.product-details {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.detail-item {
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.detail-item:last-child {
  border-bottom: none;
}

.detail-item strong {
  color: #2c3e50;
  margin-right: 10px;
}

.detail-item .price {
  font-size: 1.3rem;
  font-weight: bold;
  color: #e74c3c;
}

.description p {
  margin-top: 10px;
  line-height: 1.6;
  color: #666;
}

.modal-actions {
  display: flex;
  gap: 15px;
  margin-top: 30px;
}

.modal-actions .btn {
  flex: 1;
  padding: 12px 24px;
  font-size: 1rem;
}

@media (max-width: 768px) {
  .search-stats {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }

  .stats-info {
    flex-direction: column;
    gap: 10px;
  }

  .sort-options {
    justify-content: center;
  }

  .products-grid {
    grid-template-columns: 1fr;
  }

  .product-detail-grid {
    grid-template-columns: 1fr;
    gap: 20px;
  }

  .modal-content {
    width: 95%;
    margin: 20px;
  }

  .modal-header,
  .modal-body {
    padding: 20px;
  }
}
</style>
